<template>
  <div>
    <el-button type="primary" icon="el-icon-plus" @click="addDialog">添加</el-button>

    <el-table :data="trademarckList" border style="width: 100%; margin: 20px 0">
      <el-table-column label="序号" type="index" align="center " width="80">
      </el-table-column>

      <el-table-column prop="tmName" label="品牌名称" width="width">
      </el-table-column>

      <el-table-column label="品牌LOGO" width="width">
        <template slot-scope="{ row, $index }">
          <img :src="row.logoUrl" alt="" style="width: 80px; height: 60" />
        </template>
      </el-table-column>

      <el-table-column label="操作" width="width">
        <template slot-scope="{ row, $index }">
          <el-button type="warning" icon="el-icon-edit" @click="deleteTradeMarck(row)" >删除</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="upDataDialog(row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="getTrademarck"
      style="text-align: center"
      :current-page="page"
      :page-sizes="[3, 5, 7]"
      :page-size="limt"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
    >
    </el-pagination>

    <el-dialog :title="tmform.id ?  '修改品牌':'添加品牌'" :visible.sync="dialogFormVisible">
      <el-form :model="tmform" style="width: 80%" :rules="rules" ref="tmform">
        <el-form-item label="品牌名称" label-width="100px"  prop="tmName">
          <el-input v-model="tmform.tmName" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
              class="avatar-uploader"
              action="/dev-api/admin/product/fileUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
            <img v-if="tmform.logoUrl" :src="tmform.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过2MB</div>
          </el-upload>
        </el-form-item>
      </el-form>

        


      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmUpDialog">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Trademark",
  data() {
    return {
      page: 1,
      limt: 3,
      trademarckList: [],
      total: 0,
      dialogFormVisible: false,
      tmform: {
        tmName: "",
        logoUrl:'',
      },
      rules: {
         tmName: [
           { required: true, message: '请输入品牌名称', trigger: 'blur' },
           { min: 2, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
         ],
         logoUrl: [
           { required: true, message: '请上传品牌LOGO', trigger: 'change' }
         ],
      }
    };
  },
  mounted() {
    this.getTrademarck();
  },
  methods: {
    async getTrademarck(page = 1) {
      this.page = page;
      let result = await this.$API.trademark.getPageList(this.page, this.limt);
      if (result.code === 200) {
        this.trademarckList = result.data.records;
        this.total = result.data.total;
      } else {
        this.$message.error("网络链接失败");
      }
    },
    //点击添加品牌LOGO的回调
    addDialog(){
      this.dialogFormVisible = true;
      this.tmform = {
        tmName: "",
        logoUrl:'',
      }
    },
    //修改每页数量堵的回调
    handleSizeChange(size) {
      this.limt = size;
      this.getTrademarck();
    },

    handleAvatarSuccess(res, file) {
        // this.imageUrl = URL.createObjectURL(file.raw);
        this.tmform.logoUrl =  res.data;
    },
    beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
    },
    //点击修改的回调
    upDataDialog(row){
      this.dialogFormVisible = true;
      this.tmform = {
        ...row
      };
    },
    //更新品牌弹框的确认按钮
    confirmUpDialog(){
      this.$refs.tmform.validate( async(valid) => {
          if (valid) {
              let data = this.tmform;
              try {
                const result = await this.$API.trademark.updateBaseTrademark(data);
                this.$message.success(data.id ? "修改品牌成功" : "添加品牌成功");
                this.dialogFormVisible = false;
                this.getTrademarck(data.id ? this.page : 1);
              } catch (error) {
                this.$message.error("网络超时，请求失败")
              }
          } else {
            this.$message.error("表单校验失败")
            return false;
          }
        });
    },
    //删除品牌按钮
    deleteTradeMarck(row) {
        this.$confirm(`此操作将永久删除:${row.tmName}。 是否继续?`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            const result = await this.$API.trademark.delTradeMarck(row.id);
            this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getTrademarck(this.trademarckList.length > 1 ? this.page : this.page - 1);
          } catch (error) {
            this.$message.error("网络连接超时！删除失败");
          }
          
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      }
  },
};
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>